package com.itboye.mengwu.app.ui.mymeng.personsettings;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout.LayoutParams;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.location.Poi;
import com.itboye.core.alert.ByAlert;
import com.itboye.core.object.BaseActivity;
import com.itboye.core.object.ResultEntity;
import com.itboye.core.object.SpPublicParams;
import com.itboye.core.utils.SPUtils;
import com.itboye.mengwu.R;
import com.itboye.mengwu.addaddress.iosdialog.widget.MyAlertDialog;
import com.itboye.mengwu.addaddress.view.wheelcity.adapters.AbstractWheelTextAdapter;
import com.itboye.mengwu.addaddress.view.wheelcity.adapters.ArrayWheelAdapter;
import com.itboye.mengwu.addaddress.wheelcity.AddressData;
import com.itboye.mengwu.addaddress.wheelcity.OnWheelChangedListener;
import com.itboye.mengwu.addaddress.wheelcity.WheelView;
import com.itboye.mengwu.address.AddressFragment.GetInforListener;
import com.itboye.mengwu.address.AddressSelectView3;
import com.itboye.mengwu.data.model.AddAddressSuccessBean;
import com.itboye.mengwu.data.model.AddressQueryModel;
import com.itboye.mengwu.data.presenter.AddressQueryPresenter;

import java.util.List;
import java.util.Observable;
import java.util.Observer;

/**
 * 
 * @author 地址类管理
 * 
 */
public class AddAddressActivity extends BaseActivity implements
		OnClickListener, Observer, GetInforListener {
	ImageView img_other,  back;
	PopupWindow popupWindow;
	TextView txt_save;
	EditText input_receiver_people, input_pwd, input_address_detail,
			input_code;
	TextView input_address_choose;
	int screenWidth, screenHeight;
	String context;
	String country = "", province, city, district, provinceId, cityId,
			districtId;
	RelativeLayout re_address;
	CheckBox ch;
	AddressQueryModel model;
	AddressQueryPresenter addressQueryPresenter;
	private AddressSelectView3 addressselect3;
	protected String cityTxt;
	TextView txt_title;
	public LocationClient mLocationClient = null;
	public BDLocationListener myListener = new MyLocationListener();
	public String addr;
	String addresss;
	ImageView cerCode_button;
	@Override
	public int initView() {
		// TODO Auto-generated method stub
		return R.layout.activity_address_add;
	}

	@Override
	public void onMyCreate() {
		model = new AddressQueryModel();
		addressQueryPresenter = new AddressQueryPresenter(this);
		uid = (String) SPUtils.get(this, null, SpPublicParams.UID, "");
		txt_title.setText("新增地址");
		input_address_choose.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				View view = dialogm();
				final MyAlertDialog dialog1 = new MyAlertDialog(
						AddAddressActivity.this).builder().setTitle("选择地区")
						.setView(view)
						.setNegativeButton("取消", new OnClickListener() {
							@Override
							public void onClick(View v) {

							}
						});
				dialog1.setPositiveButton("保存", new OnClickListener() {
					@Override
					public void onClick(View v) {
						System.out.println("省" + province + "市" + city + "区"
								+ district + "id1" + provinceId + "cityId"
								+ cityId + "dis" + districtId);
						input_address_choose.setText(province + "省" + city
								+ "市" + district);
					}
				});
				dialog1.show();
			}
		});
		cerCode_button.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				mLocationClient = new LocationClient(getApplicationContext()); // 声明LocationClient类
				mLocationClient.registerLocationListener(myListener);
				initLocation();
			}
		});
		txt_save.setVisibility(View.VISIBLE);
		back.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				finish();
			}
		});

	}

	private void initLocation() {
		LocationClientOption option = new LocationClientOption();
		option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
		option.setCoorType("bd09ll");// 可选，默认gcj02，设置返回的定位结果坐标系
		int span = 1000;
		option.setScanSpan(span);
		option.setIsNeedAddress(true);// 可选，设置是否需要地址信息，默认不需要
		option.setOpenGps(true);// 可选，默认false,设置是否使用gps
		option.setLocationNotify(true);
		option.setIsNeedLocationDescribe(true);
		option.setIsNeedLocationPoiList(true);
		option.setIgnoreKillProcess(false);
		option.SetIgnoreCacheException(false);
		option.setEnableSimulateGps(false);// 可选，默认false，设置是否需要过滤gps仿真结果，默认需要
		mLocationClient.setLocOption(option);
		mLocationClient.start();
	}
	public class MyLocationListener implements BDLocationListener {

		@Override
		public void onReceiveLocation(BDLocation location) {
			// Receive Location
			StringBuffer sb = new StringBuffer(256);
			sb.append(location.getRadius());
			if (location.getLocType() == BDLocation.TypeGpsLocation) {// GPS定位结果
				sb.append("\naddr : ");
				sb.append(location.getAddrStr());
				district=location.getDistrict();
				addresss = location.getAddrStr();
				city=location.getCity();
				province=location.getProvince();

				input_address_choose.setText(location.getProvince()+location.getCity()+location.getDistrict());
				Log.d("hu",
						location.getAddrStr() + "getCountry()"
								+ location.getCountry());
				sb.append("\ndescribe : ");
				sb.append("gps定位成功");
//				getproviceNum(location.getProvince(), location.getCity());
				// provinceNo=asv.getproviceNum(location.getProvince());

			} else if (location.getLocType() == BDLocation.TypeNetWorkLocation) {// 网络定位结果
				sb.append("\naddr : ");
				sb.append(location.getAddrStr()); // 运营商信息
				addr = location.getAddrStr();
				country=location.getCountry();
				district=location.getDistrict();
				addresss = location.getAddrStr();
				city=location.getCity();
				province=location.getProvince();
				input_address_choose.setText(location.getProvince()+location.getCity()+location.getDistrict());
				location.getCity();
				String getcity = "";
				if (location.getCity() != null) {
					getcity = location.getCity();
				}
//				getproviceNum(location.getProvince(), getcity);
				sb.append("网络定位成功");
			} else if (location.getLocType() == BDLocation.TypeOffLineLocation) {// 离线定位结果
				sb.append("\ndescribe : ");
				sb.append("离线定位成功，离线定位结果也是有效的");
			} else if (location.getLocType() == BDLocation.TypeServerError) {
				sb.append("\ndescribe : ");
				sb.append("服务端网络定位失败，可以反馈IMEI号和大体定位时间到loc-bugs@baidu.com，会有人追查原因");
			} else if (location.getLocType() == BDLocation.TypeNetWorkException) {
				sb.append("\ndescribe : ");
				sb.append("网络不同导致定位失败，请检查网络是否通畅");
			} else if (location.getLocType() == BDLocation.TypeCriteriaException) {
				sb.append("\ndescribe : ");
				sb.append("无法获取有效定位依据导致定位失败，一般是由于手机的原因，处于飞行模式下一般会造成这种结果，可以试着重启手机");
			}
			sb.append("\nlocationdescribe : ");
			sb.append(location.getLocationDescribe());// 位置语义化信息
			Log.d("hu",
					location.getLocationDescribe() + "位置语义化信息"
							+ location.getCountry());
			List<Poi> list = location.getPoiList();// POI数据 if (list != null) {
			sb.append("\npoilist size = : ");
			Log.d("hu", sb.toString() + "sb");
		}
	}

	private View dialogm() {
		View contentView = LayoutInflater.from(this).inflate(
				R.layout.wheelcity_cities_layout, null);
		final WheelView country = (WheelView) contentView
				.findViewById(R.id.wheelcity_country);
		country.setVisibleItems(3);
		country.setViewAdapter(new CountryAdapter(this));

		final String cities[][] = AddressData.CITIES;
		final String ccities[][][] = AddressData.COUNTIES;
		final WheelView city = (WheelView) contentView
				.findViewById(R.id.wheelcity_city);
		city.setVisibleItems(0);

		// 地区选择
		final WheelView ccity = (WheelView) contentView
				.findViewById(R.id.wheelcity_ccity);
		ccity.setVisibleItems(0);// 不限城市

		country.addChangingListener(new OnWheelChangedListener() {
			public void onChanged(WheelView wheel, int oldValue, int newValue) {
				try {
					updateCities(city, cities, newValue);
					province = AddressData.PROVINCES[country.getCurrentItem()];
					AddAddressActivity.this.city = AddressData.CITIES[country
							.getCurrentItem()][city.getCurrentItem()];
					district = AddressData.COUNTIES[country.getCurrentItem()][city
							.getCurrentItem()][ccity.getCurrentItem()];
					provinceId = AddressData.P_ID[country.getCurrentItem()]
							+ "";
					cityId = AddressData.C_ID[country.getCurrentItem()][city
							.getCurrentItem()] + "";
					districtId = AddressData.C_C_ID[country.getCurrentItem()][city
							.getCurrentItem()][ccity.getCurrentItem()] + "";
				} catch (Exception e) {
					// TODO: handle exception
				}

			}
		});

		city.addChangingListener(new OnWheelChangedListener() {
			public void onChanged(WheelView wheel, int oldValue, int newValue) {
				updatecCities(ccity, ccities, country.getCurrentItem(),
						newValue);
				try {
					province = AddressData.PROVINCES[country.getCurrentItem()];
					AddAddressActivity.this.city = AddressData.CITIES[country
							.getCurrentItem()][city.getCurrentItem()];
					district = AddressData.COUNTIES[country.getCurrentItem()][city
							.getCurrentItem()][ccity.getCurrentItem()];
					provinceId = AddressData.P_ID[country.getCurrentItem()]
							+ "";
					cityId = AddressData.C_ID[country.getCurrentItem()][city
							.getCurrentItem()] + "";
					districtId = AddressData.C_C_ID[country.getCurrentItem()][city
							.getCurrentItem()][ccity.getCurrentItem()] + "";
				} catch (Exception e) {
					// TODO: handle exception
				}
			}
		});

		ccity.addChangingListener(new OnWheelChangedListener() {
			public void onChanged(WheelView wheel, int oldValue, int newValue) {
				province = AddressData.PROVINCES[country.getCurrentItem()];
				AddAddressActivity.this.city = AddressData.CITIES[country
						.getCurrentItem()][city.getCurrentItem()];
				district = AddressData.COUNTIES[country.getCurrentItem()][city
						.getCurrentItem()][ccity.getCurrentItem()];
				provinceId = AddressData.P_ID[country.getCurrentItem()] + "";
				cityId = AddressData.C_ID[country.getCurrentItem()][city
						.getCurrentItem()] + "";
				districtId = AddressData.C_C_ID[country.getCurrentItem()][city
						.getCurrentItem()][ccity.getCurrentItem()] + "";
			}
		});

		country.setCurrentItem(1);// 设置北京
		city.setCurrentItem(1);
		ccity.setCurrentItem(1);
		return contentView;
	}

	private void showPopupQuYuWindow(View view) {

		View contentView = LayoutInflater.from(this).inflate(
				R.layout.fragment_chooseaddress, null);
		addressselect3 = (AddressSelectView3) contentView
				.findViewById(R.id.addressselect);

		contentView.findViewById(R.id.btn_confirm).setOnClickListener(
				new OnClickListener() {

					@Override
					public void onClick(View v) {

					}
				});

		popupWindow = new PopupWindow(contentView, LayoutParams.MATCH_PARENT,
				LayoutParams.WRAP_CONTENT);

		// 一个自定义的布局，作为显示的内容
		popupWindow.setTouchable(true);
		popupWindow.setBackgroundDrawable(new BitmapDrawable());
		popupWindow.setFocusable(true);
		popupWindow.setOutsideTouchable(true);
		popupWindow.showAsDropDown(view);

		// popupWindow.setBackgroundDrawable(new BitmapDrawable());

	}

	// 接收地址

	@Override
	protected void onActivityResult(int arg0, int arg1, Intent arg2) {
		// TODO Auto-generated method stub
		super.onActivityResult(arg0, arg1, arg2);
		// arg0接收传过来的标记agr2是接收过来的值
		if (arg0 == 0 && arg1 == 1) {
			input_address_choose.setText(arg2.getStringExtra("context"));

		} else {
			input_address_choose.setText("");
		}
	}

	public void onPoPuWindow() {

	}

	private String uid;
	private String id;
	private int isDefault;

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.img_other:

			break;
		case R.id.txt_save:
			String people = input_receiver_people.getText().toString().trim();
			String phone = input_pwd.getText().toString().trim();
			String addrDetail = input_address_detail.getText().toString();
			String code = input_code.getText().toString().trim();
			if (ch.isChecked()) {
				isDefault = 1;
			} else {
				isDefault = 0;
			}
			model = new AddressQueryModel();
			model.setUid(uid);
			model.setCountry(country);
			model.setProvinceid(provinceId);
			model.setCityid(cityId);
			model.setAreaid(districtId);
			model.setDetailinfo(addrDetail);
			model.setContactname(people);
			model.setMobile(phone);
			model.setPostal_code(code);
			model.setArea(district);
			model.setProvince(province);
			model.setCity(city);
			model.setDefault(isDefault);
			addressQueryPresenter.add(model);
			break;
		default:
			break;
		}
	}

	@Override
	public void update(Observable observable, Object data) {
		// TODO Auto-generated method stub
		ResultEntity entity = handlerError(data);
		if (entity != null) {
			if (entity.getEventType() == AddressQueryPresenter.AddressAddSuccessEvent) {
				AddAddressSuccessBean addAddressSuccessBean = (AddAddressSuccessBean) entity
						.getData();
				// ByAlert.alert(addAddressSuccessBean.getId());
				setResult(102);
				finish();
			} else if (entity.getEventType() == AddressQueryPresenter.AddressAddFailEvent) {
				ByAlert.alert("添加收货地址失败");
			} else if (entity.getEventType() == AddressQueryPresenter.AddressSetDefaultSuccessEvent) {
				ByAlert.alert("添加收货地址成功(该地址为默认地址)");
				setResult(102);
				finish();
			} else if (entity.getEventType() == AddressQueryPresenter.AddressSetDefaultFailEvent) {
				ByAlert.alert("添加收货地址失败");
			}
		} else {
			System.out.println("空了");
		}
	}

	@Override
	public void onGetinforListener(String province, String city,
			String district, String provinceNo, String cityNo, String districtNo) {
		country = "86";
		this.province = province;
		this.city = city;
		this.district = district;
		this.provinceId = provinceNo;
		this.cityId = cityNo;
		this.districtId = districtNo;
		if (city.equals("市辖区") | city.equals("县"))
			city = "";
		if (district.equals("市辖区"))
			district = "";
		input_address_choose.setText(province + city + district);
	}

	@Override
	public void onSaveInstanceState(Bundle outState,
			PersistableBundle outPersistentState) {
		// TODO Auto-generated method stub
		// super.onSaveInstanceState(outState, outPersistentState);
	}

	/**
	 * Updates the city wheel
	 */
	private void updateCities(WheelView city, String cities[][], int index) {
		ArrayWheelAdapter<String> adapter = new ArrayWheelAdapter<String>(this,
				cities[index]);
		adapter.setTextSize(18);
		city.setViewAdapter(adapter);
		city.setCurrentItem(0);
	}

	/**
	 * Updates the ccity wheel
	 */
	private void updatecCities(WheelView city, String ccities[][][], int index,
			int index2) {
		ArrayWheelAdapter<String> adapter = new ArrayWheelAdapter<String>(this,
				ccities[index][index2]);
		adapter.setTextSize(18);
		city.setViewAdapter(adapter);
		city.setCurrentItem(0);
	}

	/**
	 * Adapter for countries
	 */
	private class CountryAdapter extends AbstractWheelTextAdapter {
		// Countries names
		private String countries[] = AddressData.PROVINCES;

		/**
		 * Constructor
		 */
		protected CountryAdapter(Context context) {
			super(context, R.layout.wheelcity_country_layout, NO_RESOURCE);
			setItemTextResource(R.id.wheelcity_country_name);
		}

		@Override
		public View getItem(int index, View cachedView, ViewGroup parent) {
			View view = super.getItem(index, cachedView, parent);
			return view;
		}

		@Override
		public int getItemsCount() {
			return countries.length;
		}

		@Override
		protected CharSequence getItemText(int index) {
			return countries[index];
		}
	}
}
